import math
import time
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import quad


# 定义余弦脉冲函数
def cos_pulse(t, shift, width):
    return np.cos(math.pi / width / 2 * (t - shift)) * ((-width <= t - shift) & (t - shift <= width))

# 计算两个余弦脉冲的重合面积
def overlap_area(pred_width, target_width, t1, t2):
    px1, px2 = t1 - pred_width, t1 + pred_width
    tx1, tx2 = t2 - target_width, t2 + target_width

    union_x1 = min(px1, tx1)
    union_x2 = max(px2, tx2)

    area_over = 1
    area_max = 1
    integrand = lambda t: cos_pulse(t, t1, pred_width) * cos_pulse(t, t2, target_width)
    area_over, _ = quad(integrand, union_x1, union_x2)

    area_a = 4 / math.pi * pred_width
    area_b = 4 / math.pi * target_width
    return area_over,area_max, area_a, area_b


# 计算两个余弦脉冲的总覆盖面积

def calculate_iou(preds,target, pred_width, target_width):
    s_overlap, s_a, s_b,s_max = overlap_area(pred_width, target_width, preds, target)

    iou = s_overlap / (s_a + s_b - s_overlap+1e-9)
    return iou, s_overlap


# 参数设置
width = 20
pred_width = width *3.14
target_width = width /2
target = -22.456  # 目标中心点位置固定为0
T1 = time.time()

# 遍历pred从-80到80
preds = np.linspace(-80, 80, 161)  # 161个点，包括-80和80
ious, s_overlap = zip(*[calculate_iou(pred,target, pred_width=pred_width, target_width=target_width) for pred in preds])

# 计算1 - iou
one_minus_ious = [1 - iou for iou in ious]
T2 = time.time()
print('程序运行时间:%s毫秒' % ((T2 - T1)*1000))


# 绘图
plt.figure(figsize=(10, 6))
# plt.plot(preds, one_minus_ious, marker='o', label='1 - IoU')
plt.plot(preds, ious, marker='o', label='IoU')
# plt.plot(preds, s_overlap, marker='x', label='Intersection')
# plt.plot(preds, unions, marker='s', label='Union')

# widths = [1, 3, 5]
# t = np.linspace(-10, 10, 1000)
# shift = -5
#
# for width in widths:
#     plt.plot(t, cos_pulse(t, shift, width), label=f'width={width}')
plt.title('1 - IoU, Intersection, and Union vs Prediction Offset')
plt.xlabel('Prediction Offset')
plt.ylabel('Values')
plt.legend()
plt.grid(True)
plt.show()

